package close.mazegame.collision;

import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.Manifold;

public class CollisionListener implements ContactListener {

	public CollisionListener() {
	}

	@Override
	public void beginContact(Contact contact) {
		Body b1 = contact.getFixtureA().getBody();
		Body b2 = contact.getFixtureB().getBody();
		if (b1.getUserData() instanceof Collidable && b2.getUserData() instanceof Collidable) {
			processCollison((Collidable)b1.getUserData(), (Collidable)b2.getUserData());
		}
	}

	@Override
	public void endContact(Contact contact) {
		Body b1 = contact.getFixtureA().getBody();
		Body b2 = contact.getFixtureB().getBody();
		if (b1.getUserData() instanceof Collidable && b2.getUserData() instanceof Collidable) {
			Collidable c1 = (Collidable)(b1.getUserData());
			Collidable c2 = (Collidable)(b2.getUserData());
			c1.endContact(c2);
			c2.endContact(c1);
		}
	}

	@Override
	public void preSolve(Contact contact, Manifold oldManifold) {
	}

	@Override
	public void postSolve(Contact contact, ContactImpulse impulse) {
	}

	private void processCollison(Collidable c1, Collidable c2) {
		//System.out.println(c1.getClass() + " collides with " + c2.getClass());
		
		if (c1.isRemoved() || c2.isRemoved()) {
			return;
		}
		
		c1.startContact(c2);
		c2.startContact(c1);
	}

}
